/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: service_skeleton.h
 *
 * Purpose: service skeleton base class implementation
 *
 * Developer:
 *   wen.gu , 2020-04-21
 *
 * TODO:
 *
 ***************************************************************************/

#ifndef __ARA_COM_SERVICE_SKELETON_H__
#define __ARA_COM_SERVICE_SKELETON_H__
/******************************************************************************
 **    INCLUDES
 ******************************************************************************/

#include "ara/com/types.h"
#include "ara/core/result.h"
#include "ara/core/error_code.h"
#include "ara/core/instance_specifier.h"
#include "ara/core/future.h"
#include "ara/com/runtime/function_wrapper.h"
#include "ara/com/runtime/deserializer.h"
#include "ara/com/runtime/serializer.h"
#include "ara/com/runtime/message.h"
#include "ara/com/com_error_domain.h"
#include "ara/core/vector.h"


/******************************************************************************
 **    MACROS
 ******************************************************************************/


/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/
namespace ara
{
namespace com
{
namespace skeleton
{
using SkeletonReceiveHandler = std::function<void(std::shared_ptr<ara::com::runtime::Message>)> ;
/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/

class ServiceSkeleton
{
    using InstanceIdentifier = ara::com::InstanceIdentifier;
    using MethodCallProcessingMode = ara::com::MethodCallProcessingMode;    
    using InstanceSpecifier = ara::core::InstanceSpecifier;

    template<typename T>
    using Future = ara::core::Future<T>;

    using BindingTypeArray = ara::core::Vector<NetworkBindingType>;
public:
    class ConstructionToken;

    template<typename T>
    using Result = ara::core::Result<T>;

    using DeserializerPtr = ara::com::runtime::DeserializerPtr;
    using SerializerPtr = ara::com::runtime::SerializerPtr;
    using MessagePtr = ara::com::runtime::MessagePtr;
    using MessageType = ara::com::runtime::MessageType;

public:
    class ConstructionToken
    {
    public:
        ConstructionToken(ara::com::InstanceIdentifierContainer instanceIDs, MethodCallProcessingMode mode);
        ConstructionToken(ConstructionToken&& other);
        ConstructionToken& operator=(ConstructionToken&& other);
    public:
        ConstructionToken(const ConstructionToken&) = delete;
        ConstructionToken& operator=(const ConstructionToken&) = delete;
    private:
        ara::com::InstanceIdentifierContainer mInstIds;
        MethodCallProcessingMode mMode;
        friend class ServiceSkeleton;
    };
public:
    /**
     *@param InstanceIdentifier: The identifier of a specific instance of a service, needed
     *       to distinguish different instances of exactly the same service in the system
     *
     *@param MethodCallProcessingMode: As a default argument, this is the mode of
     *       the service implementation for processing service method invocations with
     *       kEvent as default value
     */
    ServiceSkeleton(InstanceIdentifier instanceID, 
                    MethodCallProcessingMode mode = MethodCallProcessingMode::kEvent);


    /**
     *@param InstanceSpecifier: The specifiers of a specific instance of a service, needed
     *       to distinguish different instances of exactly the same service in the system
     *
     *@param MethodCallProcessingMode: As a default argument, this is the mode of
     *       the service implementation for processing service method invocations with
     *       kEvent as default value
     */
    ServiceSkeleton(InstanceSpecifier instanceSpec,
                    MethodCallProcessingMode mode = MethodCallProcessingMode::kEvent);


    /**
     *@param InstanceIdentifierContainer: The container of instances of a service,
     *       each instance element needed to distinguish different instances of exactly the
     *       same service in the system
     *
     *@param MethodCallProcessingMode: As a default argument, this is the mode of
     *       the service implementation for processing service method invocations with
     *       kEvent as default value
     */
    ServiceSkeleton(ara::com::InstanceIdentifierContainer instanceIDs,
                    MethodCallProcessingMode mode = MethodCallProcessingMode::kEvent);

    ServiceSkeleton(ConstructionToken&& other) noexcept;
    ServiceSkeleton(ServiceSkeleton&& other) noexcept;
    ServiceSkeleton(const ServiceSkeleton&) = delete;

    virtual ~ServiceSkeleton();
public:    
    ServiceSkeleton& operator=(const ServiceSkeleton&) = delete;
    ServiceSkeleton& operator=(ServiceSkeleton &&);
public:
    /**
     *@param InstanceIdentifier: The identifier of a specific instance of a service, needed
     *       to distinguish different instances of exactly the same service in the system
     *
     *@param MethodCallProcessingMode: As a default argument, this is the mode of
     *       the service implementation for processing service method invocations with
     *       kEvent as default value
     */
    static Result<ConstructionToken> Preconstruct(InstanceIdentifier instanceID,  MethodCallProcessingMode mode = MethodCallProcessingMode::kEvent);


    /**
     *@param InstanceSpecifier: The specifiers of a specific instance of a service, needed
     *       to distinguish different instances of exactly the same service in the system
     *
     *@param MethodCallProcessingMode: As a default argument, this is the mode of
     *       the service implementation for processing service method invocations with
     *       kEvent as default value
     */
    static Result<ConstructionToken> Preconstruct(InstanceSpecifier instanceSpec,  MethodCallProcessingMode mode = MethodCallProcessingMode::kEvent);

    /**
     *@param InstanceIdentifierContainer: The container of instances of a service,
     *       each instance element needed to distinguish different instances of exactly the
     *       same service in the system
     *
     *@param MethodCallProcessingMode: As a default argument, this is the mode of
     *       the service implementation for processing service method invocations with
     *       kEvent as default value
     */
    static Result<ConstructionToken> Preconstruct(ara::com::InstanceIdentifierContainer instanceIDs,  MethodCallProcessingMode mode = MethodCallProcessingMode::kEvent);
public:
    void OfferService();
    void StopOfferService();

    /**only for MethodCallProcessingMode::kPoll, otherwise throw exception */
    ara::core::Future<bool> ProcessNextMethodCall();

public: /**todo, refine me, only used by cm implementation, not for user */
    /**todo define some special functon to implementation method call */

    virtual DeserializerPtr GetDeserializer(const NetworkBindingType& type, uint8_t* data, uint32_t size);
    virtual SerializerPtr GetSerializer(const NetworkBindingType& type);
    virtual MessagePtr MakeMessage(const NetworkBindingType& bindType, MessageType type);

    virtual void RegisterReceiveHandler(const ara::core::String& name, MessageType mt, SkeletonReceiveHandler handler);
    virtual bool SendResponse(MessagePtr msg);
    virtual bool SendError(MessagePtr msg, ComErrc err);

    virtual bool SendEvent(MessagePtr msg);
    virtual bool SendFeildAck(MessagePtr msg);

    virtual const BindingTypeArray& GetBindingTypes(void);

protected: /**for register methods for sub class */
    template<class Provider, typename R, typename... Args>
    void HandleMethod(const ara::core::String& name, Provider* pr, Future<R>(Provider::* method)(Args...))
    {
        RegisterReceiveHandler(name, MessageType::kRequest, [pr](MessagePtr msg)
        {
            std::tuple<Args...> params;
            DeserializerPtr desp = GetDeserializer(msg->bindingType, msg->payload.get(), msg->payloadSize);
            if (desp)
            {
                bool parse_ret = true;
                for (size_t i = 0; i < sizeof ...(Args); i++)
                {
                    if (desp->Read(std::get<i>(params)) == false)
                    {
                        parse_ret = false;
                        break;
                    }
                }

                if (parse_ret)
                {
                    Future<R> ret = Apply(pr, method, params);

                    ret.then([this, msg](ara::core::Future<R>&& f)->bool
                        {
                            try
                            {
                                R r = f.get();

                                SerializerPtr serializer = GetSerializer(msg->bindingType);
                                serializer->Write(r);
                                msg->payload = serializer->GetPayload(msg->payloadSize);

                                return SendResponse(msg);
                            }
                            catch (ComException& e)
                            { /** todo refine me */
                                return SendError(msg, e.Error().Value());
                            }
                            catch (std::exception& e)
                            {/** todo, refineme?? */
                                return SendError(msg, ComErrc::kUnknownError);
                            }
                        });
                }
            }
        });
    }

private:
    class impl;
    std::unique_ptr<impl> mImpl;
};

} /** namespace skeleton */
} /** namespace com */
} /** namespace ara */

#endif /** !__ARA_COM_SERVICE_SKELETON_H__ */

